package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.WeChatConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private WeChatProperties weChatProperties;

    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        // 1. 根据授权码发送请求到微信服务器，获取openid

        Map<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", userLoginDTO.getCode());
        map.put("grant_type", WeChatConstant.GRANT_TYPE);

        String json = HttpClientUtil.doGet(WeChatConstant.JSCODE_2_SESSION_URL, map);
        JSONObject jsonObject = (JSONObject) JSONObject.parse(json);
        String openid = jsonObject.getString("openid");

        log.info("获取到的openid为：{}", openid);
        // 2. 根据openid到数据库中查询用户信息
        User user = userMapper.findByOpenid(openid);
        if (user == null) {
            // 2.1 查询失败，用户不存在，新建用户
            user = User.builder()
                    .openid(openid)
                    .build();
            userMapper.insert(user);
        }
        // 3. 根据用户id计算token，封装vo
        // 登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);

        // 拼装VO
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(openid)
                .token(token)
                .build();


        return userLoginVO;
    }
}
